﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Admin_MusicManagement : System.Web.UI.Page
{
    static string appDir = @"music/";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadAllMusic();
            LoadGenres();
        }
    }

    private void LoadAllMusic()
    {
        Sharemp3DataContext db = new Sharemp3DataContext();

        var musiclst = from i in db.Musics
                       orderby i.MusicID descending
                       select new
                       {
                           MusicID = i.MusicID,
                           Title = i.Title,
                           ArtistName = i.Album.Artist.ArtistName,
                           AlbumName = i.Album.AlbumName,
                           GenresName = i.Genre.GenresName,
                           Cover = i.Cover,
                       };

        grvw_Music.DataSource = musiclst;
        grvw_Music.DataBind();
    }

    private void LoadGenres()
    {
        Sharemp3DataContext db = new Sharemp3DataContext();

        lst_Genres.DataSource = db.Genres;
        lst_Genres.DataTextField = "GenresName";
        lst_Genres.DataValueField = "GenresID";
        lst_Genres.DataBind();

        lst_Genres.SelectedIndex = 1;
    }

    protected void grvw_Music_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvw_Music.PageIndex = e.NewPageIndex;
        LoadAllMusic();
    }

    protected void Search(object sender, EventArgs e)
    {
        string key = txtAlbumName.Text;
        if (key != null && key.Length > 0)
        {
            using (Sharemp3DataContext db = new Sharemp3DataContext())
            {
                var albums = from i in db.Albums
                             where i.AlbumName.Contains(key)
                             select new
                             {
                                 AlbumID = i.AlbumID,
                                 AlbumName = i.AlbumName,
                                 ArtistID = i.ArtistID,
                                 ArtistName = i.Artist.ArtistName,
                                 AlbumCover = i.AlbumCover
                             };

                if (albums.Count() != 0)
                {
                    Rpt_Album_m.DataSource = albums;
                    Rpt_Album_m.DataBind();
                    album_mdiv.Style["display"] = "block";
                    albummTitle.InnerText = "Search with \"" + key + "\" - " + albums.Count() + " items";
                }
                else
                {
                    album_mdiv.Style["display"] = "none";
                    albummTitle.InnerText = "Cannot find \"" + key + "\"";
                }
            }
        }
        SearchResultPanel.Style["display"] = "block";
        SearchResultPanel.Focus();
    }

    protected void SearchtAlbum(object sender, EventArgs e)
    {
        string key = txtAlbumS.Text;
        if (key != null && key.Length > 0)
        {
            using (Sharemp3DataContext db = new Sharemp3DataContext())
            {
                var albums = from i in db.Albums
                             where i.AlbumName.Contains(key)
                             select new
                             {
                                 AlbumID = i.AlbumID,
                                 AlbumName = i.AlbumName,
                                 ArtistID = i.ArtistID,
                                 ArtistName = i.Artist.ArtistName,
                                 AlbumCover = i.AlbumCover
                             };

                if (albums.Count() != 0)
                {
                    Rpt_Album_s.DataSource = albums;
                    Rpt_Album_s.DataBind();
                    album_sdiv.Style["display"] = "block";
                    albumsTitle.InnerText = "Search with \"" + key + "\" - " + albums.Count() + " items";
                }
                else
                {
                    album_sdiv.Style["display"] = "none";
                    albumsTitle.InnerText = "Cannot find \"" + key + "\"";
                }
            }
        }
        SearchAlbumPanel.Style["display"] = "block";
        SearchAlbumPanel.Focus();
    }

    protected void SearchArtist(object sender, EventArgs e)
    {
        string key = txtArtistS.Text;
        if (key != null && key.Length > 0)
        {
            using (Sharemp3DataContext db = new Sharemp3DataContext())
            {
                var albums = from i in db.Albums
                             where i.Artist.ArtistName.Contains(key)
                             select new
                             {
                                 AlbumID = i.AlbumID,
                                 AlbumName = i.AlbumName,
                                 ArtistID = i.ArtistID,
                                 ArtistName = i.Artist.ArtistName,
                                 AlbumCover = i.AlbumCover
                             };

                if (albums.Count() != 0)
                {
                    Rpt_Album_s.DataSource = albums;
                    Rpt_Album_s.DataBind();
                    album_sdiv.Style["display"] = "block";
                    albumsTitle.InnerText = "Search with \"" + key + "\" - " + albums.Count() + " items";
                }
                else
                {
                    album_sdiv.Style["display"] = "none";
                    albumsTitle.InnerText = "Cannot find \"" + key + "\"";
                }
            }
        }
        SearchAlbumPanel.Style["display"] = "block";
        SearchAlbumPanel.Focus();
    } 

    protected void SetSelectedAlbum(object sender, CommandEventArgs e)
    {
        int albumid = Convert.ToInt32(e.CommandArgument.ToString());
        txtAlbumID.Text = " AlbumID : " + albumid;

        using (Sharemp3DataContext db = new Sharemp3DataContext())
        {
            string albumname = db.Albums.Where(i => i.AlbumID == albumid).First().AlbumName;
            txtAlbumName.Text = albumname;
        }

        SearchResultPanel.Style["display"] = "none";

        AddPanel.Style["display"] = "block";

        lnkAdd.InnerText = "Cancel";
    }

    protected void SetSelectedAlbumSearh(object sender, CommandEventArgs e)
    {
        int albumid = Convert.ToInt32(e.CommandArgument.ToString());

        using (Sharemp3DataContext db = new Sharemp3DataContext())
        {
            Album album = db.Albums.Where(i => i.AlbumID == albumid).First();
            txtAlbumS.Text = album.AlbumName;
            txtArtistS.Text = album.Artist.ArtistName; 
        }

        SearchAlbumPanel.Style["display"] = "none";

        FindPanel.Style["display"] = "block";

        lnkFind.InnerText = "Cancel";
    }

    protected void AddNewMusic(object sender, EventArgs e)
    {
        string appPath = Request.PhysicalApplicationPath;

        if (AsyncFileUpload1.HasFile && AsyncFileUpload2.HasFile)
        {
            string musicfilename = appPath + @"\" + appDir + Server.HtmlEncode(AsyncFileUpload1.FileName);
            string imagefilename = appPath + @"\" + appDir + Server.HtmlEncode(AsyncFileUpload2.FileName);

            if (!File.Exists(musicfilename) && !File.Exists(imagefilename))
            {
                Sharemp3DataContext db = new Sharemp3DataContext();

                string title = txtTitle.Text;
                int albumid = Convert.ToInt32(txtAlbumID.Text.Replace(" AlbumID : ", ""));
                int genresid = Convert.ToInt32(lst_Genres.SelectedValue);
                string filepath = appDir + Server.HtmlEncode(AsyncFileUpload1.FileName);
                string cover = appDir + Server.HtmlEncode(AsyncFileUpload2.FileName);

                AsyncFileUpload1.SaveAs(musicfilename);
                AsyncFileUpload2.SaveAs(imagefilename);

                Music newMusic = new Music(){FilePath = filepath, Title = title, AlbumID = albumid, GenresID = genresid, Cover = cover};

                db.Musics.InsertOnSubmit(newMusic);
                db.SubmitChanges();

                Response.Redirect("MusicManagement.aspx");

                txtAlbumID.Text = "";
                txtAlbumName.Text = "";
                txtTitle.Text = "";
                lst_Genres.SelectedIndex = 1;
                lblResult.Text = "";
            }
            else
            {
                if (File.Exists(musicfilename))
                {
                    lblResult.Text = " file music is existed !";
                }
                if (File.Exists(imagefilename))
                {
                    lblResult.Text = lblResult.Text + ", file image is existed !";
                }
            }
        }
        else
        { 
            lblResult.Text = "file music or image cover ?";
        }
    }

    protected void SearchMusic(object sender, EventArgs e)
    {
        string title = txtTitle.Text ?? "";
        string artist = txtArtistS.Text ?? "";
        string album = txtAlbumS.Text ?? "";

        Sharemp3DataContext db = new Sharemp3DataContext();

        var musiclst = from i in db.Musics
                       where i.Title.Contains(title) && i.Album.Artist.ArtistName.Contains(artist) && i.Album.AlbumName.Contains(album)
                       orderby i.MusicID descending
                       select new
                       {
                           MusicID = i.MusicID,
                           Title = i.Title,
                           ArtistName = i.Album.Artist.ArtistName,
                           AlbumName = i.Album.AlbumName,
                           GenresName = i.Genre.GenresName,
                           Cover = i.Cover,
                       };

        grvw_Music.DataSource = musiclst;
        grvw_Music.DataBind();
    }

    protected void HidePanel(object sender, EventArgs e)
    {
        SearchAlbumPanel.Style["display"] = "none";
    }
    protected void grvw_Music_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grvw_Music.EditIndex = e.NewEditIndex;
    }
    protected void grvw_Music_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grvw_Music.EditIndex = -1;
    }
}